package com.example.duoduo_calc;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.content.SharedPreferences;
import android.widget.Switch;

public class StartActivity extends AppCompatActivity {

    EditText mTotalEditText;
    MyOnClickListener myOnClickListener = new MyOnClickListener();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);

        mTotalEditText = findViewById(R.id.totalEditText);
        mTotalEditText.setText(String.valueOf(getTotalNumber()));

        findViewById(R.id.button_10_add_subtract).setOnClickListener(myOnClickListener);
        findViewById(R.id.button_20_add_subtract).setOnClickListener(myOnClickListener);
        findViewById(R.id.button_100_add_subtract).setOnClickListener(myOnClickListener);
        findViewById(R.id.button_99_multiplication).setOnClickListener(myOnClickListener);

        // 测试用
//        findViewById(R.id.button_20_add_subtract).callOnClick();
    }

    void setTotalNumber(int tn)
    {
        SharedPreferences.Editor editor = getSharedPreferences("tcpInfo", MODE_PRIVATE).edit();
        editor.putInt("TotalNumber", tn);
        editor.apply();
//        editor.commit();
    }

    int getTotalNumber()
    {
        SharedPreferences pref = getSharedPreferences("tcpInfo", MODE_PRIVATE);
        return pref.getInt("TotalNumber", 50);
    }

    class MyOnClickListener implements View.OnClickListener
    {
        @Override
        public void onClick(View v){
            int type = 0;
            switch (v.getId())
            {
                case R.id.button_10_add_subtract: type = 0; break;
                case R.id.button_20_add_subtract: type = 1; break;
                case R.id.button_100_add_subtract: type = 2; break;
                case R.id.button_99_multiplication: type = 3; break;
                default:
            }
            Switch s = findViewById(R.id.challengeSwitch);

            int t;
            try {
                t = Integer.valueOf(mTotalEditText.getText().toString());
            }catch(final Exception e)
            {
                if (s.isChecked() ==false) return;
                t = 0;
            }
            setTotalNumber(t);

            MainActivity.isOrientationChange = false;
            Intent intent = new Intent(StartActivity.this, MainActivity.class);
            intent.putExtra("total", t);
            intent.putExtra("type", type);
            intent.putExtra("challenge", s.isChecked());
            startActivity(intent);
        }
    }

}
